package cc.customer.expCustomer.services.imp;

import cc.customer.cAppNews.CAppNewsService;
import cc.customer.cRound.dao.CRoundConfigMapper;
import cc.customer.cRound.dao.CRoundGradeMapper;
import cc.customer.cRound.dao.CRoundLevelMapper;
import cc.customer.cRound.dao.CRoundMapper;
import cc.customer.cRound.domain.CRound;
import cc.customer.cRound.domain.CRoundConfig;
import cc.customer.cRound.domain.CRoundGrade;
import cc.customer.cRound.domain.CRoundLevel;
import cc.customer.clue.dao.ClueMapper;
import cc.customer.clue.domain.Clue;
import cc.customer.cusDynamic.dao.CusDynamicMapper;
import cc.customer.expCustomer.dao.ExEmpMapper;
import cc.customer.expCustomer.domain.ExEmp;
import cc.customer.expCustomer.services.ExEmpServices;
import cc.customer.ServicesUtils.NoticeUtils;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.FebsUtil;
import cc.customer.common.utils.Utils;
import cc.customer.cusDynamic.domain.CusDynamic;
import cc.customer.cusDynamic.services.CusDynamicService;
import cc.customer.rabbit.domain.CAppNews;
import cc.customer.rabbit.domain.CconvNotice;
import cc.customer.sendMsg.SendMagRecevicer;
import cc.customer.system.dao.DeptMapper;
import cc.customer.system.dao.ExConfigMapper;
import cc.customer.system.dao.ExConfigRecordMapper;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.Dept;
import cc.customer.system.domain.ExConfig;
import cc.customer.system.domain.ExConfigRecord;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.utils.AutonCusInfo;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hslf.record.CString;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,readOnly = true,rollbackFor = Exception.class)
public class ExEmpServicesImp extends BaseService<ExEmp> implements ExEmpServices {

    private static final Logger logger = LoggerFactory.getLogger(ExEmpServicesImp.class);
    @Autowired
    private ExConfigMapper exConfigMapper;
    @Autowired
    private ExConfigRecordMapper exConfigRecordMapper;
    @Autowired
    private ExEmpMapper exEmpMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private CusDynamicService cusDynamicService;

    @Autowired
    private CAppNewsService cAppNewsService;
    @Autowired
    private SendMagRecevicer sendMagRecevicer;
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CRoundMapper roundMapper;
    @Autowired
    private CRoundConfigMapper configMapper;
    @Autowired
    private CRoundLevelMapper levelMapper;
    @Autowired
    private CRoundGradeMapper cRoundGradeMapper;
    @Autowired
    private CusDynamicMapper dynamicMapper;


    @Override
    public List<ExEmp> getAllExEmp(ExEmp exEmp,MyUser userwer) {

        try {
            //意向等级
            String cExGroud = exEmp.getcExGroud();
            if (!StringUtils.isEmpty(cExGroud)){
                List<String> list = Arrays.asList(cExGroud.split(","));
                exEmp.setGroupArray(list);
            }
            /**地区**/
            String  cExzone = exEmp.getcExzone();
            if (!StringUtils.isEmpty(cExzone)){
                List<String> list = Arrays.asList(cExzone.split(","));
                exEmp.setZoneArray(list);
            }
            /**客户新增时间**/
            String starttime=  exEmp.getStarttime();
            String endtime = exEmp.getEndtime();
            if (!StringUtils.isAnyEmpty(starttime,endtime)){
                exEmp.setEndtime(endtime+" 23:59:59");
                exEmp.setStarttime(starttime+" 00:00:00");
            }
            /**部门*/
            String cExDept = exEmp.getcExDept();
            if (!StringUtils.isEmpty(cExDept)){
                List<String> list1 = Arrays.asList(cExDept.split(","));
                exEmp.setDeptArray(list1);
            }
            /**人员*/
            String cExReceiver = exEmp.getcExReceiver();
            if(!StringUtils.isEmpty(cExReceiver)){
                List<String> list2 = Arrays.asList(cExReceiver.split(","));
                exEmp.setPersonArray(list2);
            }

            List<ExEmp> listall = exEmpMapper.selectExtEmpList(exEmp);

            /**查询所有的员工**/
            List<MyUser> users = userService.selectAll();
            List<Dept> depts = deptMapper.selectAll();
            for (ExEmp emp:listall){
                String creator= emp.getcExCreator();
                String recive = emp.getcExReceiver();
                for (MyUser user :users){
                    if (user.getUserUuid().equals(creator)){
                        emp.setcExCreator(user.getNickname());
                    }
                    String deptid = "";
                    if (user.getUserUuid().equals(recive)){
                        emp.setcExReceiver(user.getNickname());
                        deptid = user.getDeptId()+"";

                    }
                    for(Dept dept:depts){
                        if(deptid.equals(dept.getDeptId()+"")){
                            emp.setcExCurrentDept(dept.getDeptName());
                        }
                    }
                }
                String stage = emp.getcExStage();
                if (Constant.CUSTOMER_RECORD_ZHUANRQANG.equals(stage)){
                    CusDynamic cusDynamic = cusDynamicService.selectExempChangeStatus(emp.getcExId()+"");
                    if (null != cusDynamic){
                        emp.setDealtime(cusDynamic.getDyCreattime());
                    }
                }
                /**隐藏隐秘信息**/
                AutonCusInfo.parseExEmp(emp,userwer);
            }
            return listall;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取推广资源失败："+e.getMessage());
        }
        return new ArrayList<>();
    }
    @Override
    public List<String> parseDeptUsers(String cExCurrentDept){
            List<String> list3 = Arrays.asList(cExCurrentDept.split(","));
            List<String> cdlist = new ArrayList<>();
            for(String dept:list3){
                List<MyUser> users  = userMapper.findUserByDepid(dept);
                for(MyUser user:users){
                    cdlist.add(user.getUserUuid());
                }
            }
            return cdlist;
    }
    @Override
    @Transactional
    public List<ExEmp> getAllExEmpByids(String ids,MyUser user) {
        try {
            List<String> list = Arrays.asList(ids.split(","));
            Example example = new Example(ExEmp.class);
            example.createCriteria().andIn("cExId",list);
            List<ExEmp> listEmp =  exEmpMapper.selectExportExEmpList(list);

            List<MyUser> users = userService.findUserWithDept(new MyUser());

            for (ExEmp exEmp :listEmp){
                AutonCusInfo.parseExEmp(exEmp,user);
                String ling = exEmp.getcExRetime();
                if (!StringUtils.isEmpty(ling)){
                    String cretime = exEmp.getcExTime();
                    Date lingqu = DateUtil.convert2Date(ling,"yyyy-MM-dd HH:mm:ss");
                    Date cretimeDate = DateUtil.convert2Date(cretime,"yyyy-MM-dd HH:mm:ss");
                    Long time = DateUtil.diffSecond(cretimeDate,lingqu);
                    exEmp.setcExDiffRetime(time+" 秒");
                }else{
                    exEmp.setcExDiffRetime("尚未领取");
                }
                Dept dept= new Dept();
                if(!"".equals(exEmp.getcExDept())){
                    dept.setDeptId(Long.parseLong(exEmp.getcExDept()));
                    String deptname = deptMapper.selectOne(dept).getDeptName();
                    exEmp.setcExDept(deptname);
                }
                /**处理人**/
                /*for (MyUser user1 :users){
                    String  uuid = user1.getUserUuid();

                    if (uuid.equals(exEmp.getcExCreator())){
                        exEmp.setcExCreator(user1.getNickname());
                    }
                    if (uuid.equals(exEmp.getcExReceiver())){
                        exEmp.setcExReceiver(user1.getNickname());
                        exEmp.setcExDept(user1.getDeptName());
                    }
                }*/
                String stage = exEmp.getcExStage();
                if (Constant.CUSTOMER_RECORD_ZHUANRQANG.equals(stage)){
                    CusDynamic cusDynamic = cusDynamicService.selectExempChangeStatus(exEmp.getcExId()+"");
                    if (null != cusDynamic){
                        exEmp.setDealtime(cusDynamic.getDyCreattime());
                    }
                }

            }
            return listEmp;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取推广用户失败："+e.getMessage());
        }
        return new ArrayList<>();
    }
    @Override
    @Transactional
    public ResponseBo updateExEmpInfo(ExEmp exEmp,MyUser user) {
        try {
            /**验证手机号**/
            String phone = exEmp.getcExMobile();
            if(!StringUtils.isEmpty(phone)){
               Boolean isPhone =  FebsUtil.isPhoneNo(phone);
                if (!isPhone){ return ResponseBo.error("输入得手机号格式不正确"); }
            }
            int num = this.updateNotNull(exEmp);
            if (num > 0){
                if (!StringUtils.isEmpty(exEmp.getcExStage())){
                    List<String> list = new ArrayList<>();
                    list.add(exEmp.getcExId()+"");
                    CusDynamic cus = new CusDynamic();
                    cus.setDyCreator(user.getUserUuid());
                    cus.setDyType(Constant.CUSTOMER_RECORD_STATAGES);
                    cus.setDySourceType("1");
                    String stta = AutonCusInfo.parseCustomerStage(exEmp.getcExStage());
                    cus.setDyContent(user.getNickname()+" 更改了客户阶段: "+stta);
                    cusDynamicService.inserDynamic(list,cus);
                }
                return ResponseBo.ok("修改成功");
            }
        }catch (Exception e){
            logger.error("修改推广资源信息失败:"+e.getMessage());
        }

        return ResponseBo.error("修改失败");
    }
    @Override
    @Transactional
    public ResponseBo deleteExEmp(String ids) throws RuntimeException{
        try {
            List<String> list = Arrays.asList(ids.split(","));
            ExEmp exEmp = new ExEmp();
            exEmp.setcExIsdelete("1");
            this.batchUpdate(list,"cExId",ExEmp.class,exEmp);
            cusDynamicService.deleteDynamic(list);
            return ResponseBo.ok("删除成功");
        }catch (Exception e){
            logger.error("删除推广资源失败："+e.getMessage());
            throw new RuntimeException();
        }
    }
    @Override
    public ResponseBo getExEmpDetail(String ids,MyUser user) {
        try {
            ExEmp exemp = exEmpMapper.selectExEmpDetail(ids);
            ExEmp exEmp = AutonCusInfo.parseExEmp(exemp,user);
            return ResponseBo.ok(exEmp);
        }catch (Exception e){
            logger.error("获取推广资源用户详情资料失败"+e.getMessage());
        }
        return ResponseBo.error("获取推广资料失败");
    }
    @Override
    public ResponseBo appGetExEmpDetail(String ids,MyUser user) {
        try {
            ExEmp exemp = exEmpMapper.selectExEmpDetail(ids);
            return ResponseBo.ok(exemp);
        }catch (Exception e){
            logger.error("获取推广资源用户详情资料失败"+e.getMessage());
        }
        return ResponseBo.errors("获取推广资料失败",new ExEmp());
    }
    @Override
    public ResponseBo getExEmpDetailLabel(String ids) {
        try {
            ExEmp exemp = exEmpMapper.selectExEmpLabel(ids);
            return ResponseBo.ok(exemp);
        }catch (Exception e){
            logger.error("获取推广资源用户详情资料失败"+e.getMessage());
        }
        return ResponseBo.errors("获取推广资料失败",new ExEmp());
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public ResponseBo addExEmpCustomer(ExEmp exEmp) throws Exception {
        String uuid = Utils.getUUID();
        String timeDat = DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss");
        exEmp.setcExUuid(uuid);
        exEmp.setcExIsdelete("0");
        exEmp.setcExStage("1");
        exEmp.setcExRecent("分配了客户");
        exEmp.setcExRecentTime(timeDat);
        exEmp.setcExGtime(timeDat);

        /**判断信息类型*/
        String type = parseChanelType(exEmp.getcExChanel());
        int numTixing = 0;
        try {
            /**判断是不是自动分配**/
            if (Constant.EXEMP_AUTO_DIS.equals(exEmp.getcExMethod())){
                /**自动分配部门 1:把部门和人员制空**/
                if(type.equals(Constant.CUSTOMER_EXE_DA)){
                    exEmp = handleData(exEmp);
                }else if(type.equals(Constant.CUSTOMER_EXE_XIN)){
                    exEmp.setcExDept("");
                    exEmp.setcExReceiver("");
                    /**查询模板**/
                    Example example = new Example(ExConfig.class);
                    example.createCriteria().andEqualTo("exCfgName",exEmp.getcExIntern()).andEqualTo("exCfgType",type);
                    List<ExConfig> list = exConfigMapper.selectByExample(example);
                    if (!list.isEmpty()){
                        ExConfig exConfig = list.get(0);
                        String puuid = exConfig.getExCfgUuid();
                        //查询 模板得配置项
                        List<ExConfigRecord> listconfig = exConfigRecordMapper.selectAllExModalRecordsByUuid(puuid,type);
                        ExConfigRecord curent = null;
                        if (!listconfig.isEmpty()){
                            //查询配置模板得
                            for (ExConfigRecord records :listconfig){
                                //首先判断 是不是当前轮已经分配了
                                if ("0".equals(records.getExCIsdis())){
                                    //判断是不是 还有余额
                                    int yue = Integer.valueOf(records.getExCYnum());
                                    //获取配置选项
                                    int num = Integer.valueOf(records.getExCNum());
                                    //获取本月总的shuliang
                                    int totle = Integer.valueOf(records.getExCYtotle());
                                    //获取已经分配得数量
                                    int cysle= Integer.valueOf(records.getExCCycles());
                                    //算出可支配余额
                                    int kezhipei = (num - yue);
                                    //算出本月得 yue
                                    int monthzhipei = (totle-cysle);

                                    logger.info("可支配得余额："+kezhipei);
                                    if (kezhipei > 0 && monthzhipei > 0){
                                        //增加提醒
                                        numTixing = monthzhipei;
                                        exEmp.setcExDept(records.getExCDept());
                                        curent = records;
                                        break;
                                    }
                                }
                            }

                            //结束分配 结束更新
                            if (curent == null){
                                logger.info("分配第一个用户：恢复以前得状态");
                                exConfigRecordMapper.updateExModalRecordback(puuid,type);
                                //默认分给第一个还有余额得部门  ，，恢复其他部门
                                for (ExConfigRecord records1 :listconfig){
                                    //判断是不是 还有余额
                                    int totle = Integer.valueOf(records1.getExCYtotle());
                                    //获取已经分配得数量
                                    int cysle= Integer.valueOf(records1.getExCCycles());
                                    //算出可支配余额
                                    int kezhipei = (totle - cysle);
                                    int num = Integer.valueOf(records1.getExCNum());
                                    //配置的分配 是不是大于0；
                                    if (kezhipei > 0 && num>0){
                                        //部门提醒功能
                                        numTixing = kezhipei;
                                        exConfigRecordMapper.updateExModalRecord(records1.getExCId()+"",type);
                                        exEmp.setcExDept(records1.getExCDept());
                                        break;
                                    }
                                }
                            }else{
                                //更新当前部门，，分配得+1 已分配+1
                                logger.info("分配用户：一分得 未分得 +1");
                                exConfigRecordMapper.updateExModalRecord(curent.getExCId()+"",type);
                                //是否时余额 当前配置 是不是1 如果1 则不再进行下一次分配
                                ExConfigRecord curentall =  exConfigRecordMapper.selectByPrimaryKey(curent.getExCId());
                                int yue = Integer.valueOf(curentall.getExCYnum());
                                //获取配置选项
                                int num = Integer.valueOf(curentall.getExCNum());
                                int kezhipei = (num - yue);
                                logger.info(kezhipei+" 个可支配名额");
                                if (kezhipei == 0){
                                    logger.info("重新重置 原始状态");
                                    exConfigRecordMapper.updateExModalRecordOver(curent.getExCId()+"",type);
                                }
                            }
                        }
                    }
                }
            }

            int num  = this.save(exEmp);
            if (num > 0 ){
                Example example = new Example(ExEmp.class);
                example.createCriteria().andEqualTo("cExUuid",exEmp.getcExUuid());
                ExEmp exEmp1 = this.selectByExample(example).get(0);
                exEmp1.setcExCreator(exEmp.getcExReceiver());
                if(Constant.EXEMP_AUTO_DIS.equals(exEmp.getcExMethod())){
                   /* CconvNotice notice = NoticeUtils.ExempAutoNotice(exEmp1,exEmp);
                    sendMagRecevicer.processDept(notice);*/
                }else{
                    CconvNotice notice = NoticeUtils.ExempShouNotice(exEmp1,exEmp);
                    String rid = exEmp.getcExReceiver();
                    String username = userService.findUserByUuids(rid).getUsername();
                    notice.setcConvUsers(username);
                    //sendMagRecevicer.processUser(notice);
                    /**手动分配的 增加手动分配记录**/
                    cusDynamicService.insertExEmpDis(rid,exEmp1.getcExId()+"");
                }
//                /**推送钉钉消息**/
//                if(type.equals(Constant.CUSTOMER_EXE_DA)){
//                    //创建最初领取人
//                    CusDynamic cusde = new CusDynamic();
//                    cusde.setDyUuid(Utils.getUUID());
//                    cusde.setDyCreator(exEmp.getcExReceiver());
//                    cusde.setDySourceType(Constant.ZIYUAN_TYPE_EXEMP);
//                    cusde.setDyType(Constant.CUSTOMER_RECORD_LINGQU);
//                    cusde.setDyCusUuid(exEmp.getcExId()+"");
//                    cusde.setDyContent("自动领取客户");
//                    cusde.setDyCreattime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
//                    dynamicMapper.insert(cusde);
//
//                    sendMagRecevicer.sendMsgToDingding(exEmp);
//                }else if(type.equals(Constant.CUSTOMER_EXE_XIN)){
//                    sendMagRecevicer.sendMsgForDingding(exEmp1,type);
//                }

                /**如果还是没有部门则 一直提醒**/
                if (StringUtils.isEmpty(exEmp.getcExDept())){numTixing = 0;}

                if(!StringUtils.isEmpty(exEmp.getcEclueId())){
                    Clue clue = new Clue();
                    clue.setcAccid(exEmp.getcEclueCreatid());
                    Example exe = new Example(ExEmp.class);
                    exe.createCriteria().andEqualTo("cExUuid",uuid);
                    ExEmp ee = this.selectByExample(exe).get(0);
                    clue.setcCusid(ee.getcExId()+"");
                    clue.setcLeadsid(exEmp.getcEclueId());
                    clue.setcSource(exEmp.getcESource());
                    String token = "";
                    switch (exEmp.getcEclueCreatid()){
                        case "1664749107934216":
                            token =  "0ac97728e5e37229fa44687f25465d0aaa8f138a";
                            break;
                        case "1668479048541198":
                            token =  "b12383b44c1fa35f0bf19cde4cdfb20fa6137750";
                            break;
                        default:
                    }
                    clue.setcTokenid(token);
                    clue.setcType(exEmp.getcESourType());
                    int num1 = clueMapper.insert(clue);
                    logger.info("插入回调准备数据:"+num1+"条");
                }
                return numTixing > 5 ?ResponseBo.ok(-1):ResponseBo.ok(numTixing);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("增加失败: 数据格式：  "+ exEmp.toString());
            logger.error("新增推广资源失败"+e.getMessage());
            throw new RuntimeException("新增推推广资源失败");
        }
        return ResponseBo.error("新增失败");
    }

    //判断大搜资源项目配置
    private ExEmp handleData(ExEmp exEmp){
        logger.info("测试信息流的分配方式："+exEmp.toString());
        try {
            String intern = exEmp.getcExIntern();
            Example example = new Example(CRound.class);
            example.createCriteria().andEqualTo("rName",intern);
            String lpid = roundMapper.selectByExample(example).get(0).getrUuid();
            /**解析配置**/
            pasrseInfo(exEmp,lpid);
            /**判断是不是所有的配置是不是执行完成
             * 如果完成则制空当前左右状态，从头执行
             * **/
            String userid = exEmp.getcExReceiver();
            if (StringUtils.isEmpty(userid)){
                logger.info("测试已经执行");
                /**再去执行**/
                List<CRoundConfig> configsde = configMapper.selectByPid(lpid);
                Boolean isfalse= false ;
                for (CRoundConfig cRoundConfig : configsde){
                    String totle  = cRoundConfig.getcNcount();
                    String yicount = cRoundConfig.getcYiCount();
                    if (Integer.valueOf(totle) > Integer.valueOf(yicount)){
                        isfalse = true;
                    }
                }
                if (!isfalse){
                    configMapper.updateAllCountByid(lpid);
                    levelMapper.updateLeveryiUserToIpuser(lpid);
                }
                pasrseInfo(exEmp,lpid);
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
        return exEmp;
    }
    /**分配规则**/
    private void pasrseInfo(ExEmp exEmp,String lpid) throws Exception{
        /**按照项目查询配置的分配部门**/
        List<CRoundConfig> configs = configMapper.selectByPid(lpid);

        String time  = DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss");
        for (CRoundConfig cRoundConfig:configs){
            /**判断是不是已经还没有走
             * 如果小于 当前轮数，则判断是不是还有没有分配的人数
             * **/
            String totle = cRoundConfig.getcNcount();
            String ytotle = cRoundConfig.getcYiCount();
            if(Integer.valueOf(totle)<=0 ){
                continue;
            }
            if (!StringUtils.isEmpty(ytotle)){
                if(Integer.valueOf(totle)-Integer.valueOf(ytotle)<=0 ){
                    continue;
                }
            }
            String crUuid = cRoundConfig.getcRdrecorder();

            /**查询当前轮次和当前等级分配的人数部门**/
            List<String>GradeId = Luncitype(cRoundConfig.getcGradeId());

            String cdept = cRoundConfig.getcNdeptid();
            List<String> allCdept = Arrays.asList(cdept.split(","));

            Example example2 = new Example(CRoundLevel.class);
            example2.createCriteria().andIn("lDeptid",allCdept)
                    .andEqualTo("lUuid",cRoundConfig.getcPid())
                    .andIn("lGradeid",GradeId);
            example2.setOrderByClause("l_gradeid");

            List<CRoundLevel> cRoundLevels = levelMapper.selectByExample(example2);
            /**当前轮次部门排序规则**/
            List<CRoundLevel> listall = new ArrayList<>();
            for (CRoundLevel croud:cRoundLevels){
                for (String deptid:allCdept){
                    if (croud.getlDeptid().equals(deptid)){
                        listall.add(croud);
                        break;
                    }
                }
            }
            logger.info(listall+"");
            /***
             * 判断当前配置的轮数 查询所有的人数
             * A
             * A+B
             * A+B+C
             * A+B+C+D
             * A+B+C+D+E
             * **/
            List<String> allFenUser = new ArrayList<>();
            List<String> allFenUserde = new ArrayList<>();
            listall.forEach(cdr->{
                String users = cdr.getlPerson(); //当前轮数的所有的人
                if(!StringUtils.isEmpty(users)){
                    List<String> getuser = Arrays.asList(users.split(","));
                    allFenUser.addAll(getuser);
                    allFenUserde.addAll(getuser);
                }
            });
            List<CRoundGrade> list = new ArrayList<>();
            if (!StringUtils.isEmpty(crUuid)){
                /**查询当前批次**/
                Example example1 = new Example(CRoundGrade.class);
                example1.createCriteria().andEqualTo("gUuid",crUuid);
                example1.setOrderByClause("g_creatime");
                list  = cRoundGradeMapper.selectByExample(example1);
            }
            /**如果查询分配的为空，则说明当前没有**/
            if (list.isEmpty()){
                /**分给当前批次的第一个人**/
                String uuid  = Utils.getUUID();
                String userid = allFenUser.get(0);
                //TODO(尚未处理部门)
                CRoundGrade cRoundGrade =
                        new CRoundGrade(uuid,userid,time);
                cRoundGradeMapper.insert(cRoundGrade);

                logger.info("当前分配的人员1："+userid);
                MyUser user = userService.selectUserByDingDing(userid);
                exEmp.setcExDept(user.getDeptId()+"");
                exEmp.setcExReceiver(user.getUserUuid());
                /**
                 * 跟新当前批次
                 * **/
                cRoundConfig.setcRdrecorder(uuid);
                configMapper.updateNewRound(cRoundConfig);
                break;
            }else{
                /**
                 * 判断当前轮数的人员是否分配
                 * **/
                for (CRoundGrade grade:list){
                    allFenUser.remove(grade.getgPuuid());
                }
                /**如果为不为空 说明当前轮数还有剩余**/
                if (!allFenUser.isEmpty()){
                    String userid = allFenUser.get(0);
                    CRoundGrade cRoundGrade = new CRoundGrade(crUuid,userid,time);
                    cRoundGradeMapper.insert(cRoundGrade);
                    logger.info("当前分配的人员3："+userid);
                    MyUser user = userService.selectUserByDingDing(userid);
                    exEmp.setcExDept(user.getDeptId()+"");
                    exEmp.setcExReceiver(user.getUserUuid());
                    break;
                }else{
                    String uuid = Utils.getUUID();
                    cRoundConfig.setcRdrecorder(uuid);
                    String yicout = cRoundConfig.getcYiCount();

                    cRoundConfig.setcYiCount(Integer.valueOf(yicout)+1+"");
                    configMapper.updateNewRound(cRoundConfig);
                    //判断当前的轮数
                    String pei = cRoundConfig.getcNcount();
                    if (Integer.valueOf(pei) > Integer.valueOf(yicout)+1){
                        String userid = allFenUserde.get(0);
                        CRoundGrade cRoundGrade =
                                new CRoundGrade(uuid,userid,time);
                        cRoundGradeMapper.insert(cRoundGrade);

                        logger.info("当前分配的人员4："+userid);
                        MyUser user = userService.selectUserByDingDing(userid);
                        exEmp.setcExDept(user.getDeptId()+"");
                        exEmp.setcExReceiver(user.getUserUuid());
                        break;
                    }else{
                        Example example = new Example(CRoundConfig.class);
                        example.createCriteria().andEqualTo("cPid",cRoundConfig.getcPid())
                                .andIsNull("cRdrecorder");
                            example.setOrderByClause("c_gradeid");
                        List<CRoundConfig>cRoundConfigs = configMapper.selectByExample(example);
                        for (CRoundConfig cRoundCo : cRoundConfigs) {
                            String ctotle = cRoundCo.getcNcount();
                            String yitotle = cRoundCo.getcYiCount();
                            if (Integer.valueOf(ctotle)-Integer.valueOf(yitotle) > 0  ){
                                cRoundCo.setcRdrecorder(Utils.getUUID());
                                configMapper.updateByPrimaryKey(cRoundCo);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
    }


    /**判断当前轮次**/
    private List<String> Luncitype(String groudid){
        List<String>  list  =new ArrayList<>();
        switch (groudid){
            case "1":
                list.add("1");
                break;
            case "2":
                list.add("1");list.add("2");
                break;
            case "3":
                list.add("1");list.add("2");list.add("3");
                break;
            case "4":
                list.add("1");list.add("2");list.add("3");
                list.add("4");
                break;
            case "5":
                list.add("1");list.add("2");list.add("3");
                list.add("4");list.add("5");
                break;
            default:
                list.add("1");
        }
        return list;
    }

    private static String parseChanelType(String chanel){
        String type = "";
        if("百度头条".equals(chanel)||"今日头条".equals(chanel)||"UC头条".equals(chanel)||"广点通".equals(chanel)||"凤凰新闻".equals(chanel)||"网易新闻".equals(chanel)||"抖音视频".equals(chanel)||"火山视频".equals(chanel)){
            type = "2";
        }else{
            type = "1";
        }
        return type;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public ResponseBo batchUpdateExEmp(String ids, ExEmp exEmp) throws Exception {
        try {
            List<String> cusid = Arrays.asList(ids.split(","));
            exEmp.setcExReceiver(exEmp.getcExCustomer());
            this.batchUpdate(cusid,"cExId",ExEmp.class,exEmp);
            CusDynamic cusde = new CusDynamic();
            cusde.setDyCreator(exEmp.getcExCreator());
            cusde.setDySourceType(Constant.ZIYUAN_TYPE_EXEMP);
            cusde.setDyType(Constant.CUSTOMER_RECORD_ZHUANRQANG);
            cusde.setDyZhuanUserid(exEmp.getcExCustomer());
            cusDynamicService.inserDynamic(cusid,cusde);
        }catch (Exception e){
            throw  new RuntimeException();
        }
        return ResponseBo.ok();
    }

    @Override
    public Boolean isHaveExEmpByMobileOrQqOrWechat(String mobile, String qq, String wechat) {
        try {
            Example example =  new Example(ExEmp.class);
            Example.Criteria criterion = example.createCriteria();
            criterion.andNotEqualTo("cExIsdelete","1");
            if (!StringUtils.isEmpty(mobile)){
                criterion.andEqualTo("cExMobile",mobile);
            }
            if (!StringUtils.isEmpty(qq)){
                criterion.andEqualTo("cExQq",qq);
            }
            if (!StringUtils.isEmpty(wechat)){
                criterion.andEqualTo("cExWechat",wechat);
            }
            String date = DateUtil.getCurrentDate("yyyy-MM-dd");
            criterion.andBetween("cExTime",date+" 00:00:00",date+" 23:59:59");

            List<ExEmp> list = this.selectByExample(example);
            return !list.isEmpty();
        }catch (Exception e){
            logger.error("查询网站后端数据失败:"+e.getMessage());
            return true;
        }
    }

    @Override
    public List<String> getAllExEmpPhone() {
        List<String> listNum = new ArrayList<>();
        try {
            listNum = this.exEmpMapper.getAllphone();
        }catch (Exception e){
            logger.error(""+e.getMessage());
        }
        return listNum;
    }
}
